package com.example.paopao.consumer.account.service.impl;

import com.example.paopao.common.enumerator.ServiceCode;
import com.example.paopao.common.exception.ServiceException;
import com.example.paopao.consumer.account.dao.persist.repository.IUserRepository;
import com.example.paopao.consumer.account.pojo.dto.UserRegDTO;
import com.example.paopao.consumer.account.pojo.entity.User;
import com.example.paopao.consumer.account.pojo.vo.UserVO;
import com.example.paopao.consumer.account.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserRepository userRepository;

    @Value("${paopao.jwt.secret-key}")
    private String encodePassword;

    @Override
    public void reg(UserRegDTO userRegDTO) {

        UserVO userVO = userRepository.selectByName(userRegDTO.getUsername());

        final List<UserVO> byPhone = userRepository.selectByPhone(userRegDTO.getPhone());
        /*
        * selectOne()
        * */
        if (userVO!=null ){
            String message="输入的用户已存在！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        if (byPhone.size()>0 || !byPhone.isEmpty()){
            String message="您的电话号码已注册！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }

        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String password = userRegDTO.getPassword()+encodePassword;
        String encode = encoder.encode(password);

        User user = new User();
        user.setCreateTime(LocalDateTime.now());
        BeanUtils.copyProperties(userRegDTO,user);
        user.setPassword(encode);

        userRepository.insert(user);
    }





}
